package org.xfy.org.exception;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.xfy.base.util.AjaxResult;
import org.xfy.base.util.ErrorCode;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理类
 */
//@ControllerAdvice
@RestControllerAdvice //符合注解：RestController类的增强  - 可以指定包
public class GlobalExceptionHandler {

    //捕获业务异常
    //捕捉BusinessException异常: 应用到所有@RequestMapping的方法上，在其抛出BusinessException时执行
    @ExceptionHandler(BusinessException.class)
    public AjaxResult globleException(BusinessException e){
        e.printStackTrace();
        String code = e.getMessage();
        ErrorCode errorCode = ErrorCode.getErrorCodeBycode(code);
        return AjaxResult.me().setErrorCode(errorCode);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidException(MethodArgumentNotValidException e){
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> collect = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        //将list里面的数据转为String ,号隔开
        String join = String.join(",", collect);
        return AjaxResult.me().setSuccess(false).setMessage(join);
    }
    //捕获非业务异常
    //捕捉其他异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exception(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setErrorCode(ErrorCode.SYSTEM_ERROR);
    }
}
//1.对controller进行增强 2.捕获指定异常 3.对异常进行处理